<template>
  <div class="wrap">
    <toolbarTop :left="left" @refresh="refresh" @add="add" @del="del">
      <template #leftSuffix>
        <a-space :size="5">
          <a-dropdown class="ml5">
            <template v-slot:overlay>
              <a-menu>
                <a-menu-item v-for="item in groupData" :key="item.group_id" @click="handleMove(item.group_id)">
                  {{ item.group_name }}
                </a-menu-item>
              </a-menu>
            </template>
            <a-button>
              移动至
              <DownOutlined />
            </a-button>
          </a-dropdown>
          <a-upload
            v-model:fileList="fileList"
            name="file"
            :multiple="true"
            :action="BASE_URL + `/admin_api.php/upload/image`"
            @change="handleChange"
            :data="{
              group_id: selectedKeys[0]
            }"
            :show-upload-list="false"
            :headers="{
              Authorization: $store.state.token
            }"
          >
            <a-button>
              <UploadOutlined />
              上传
            </a-button>
          </a-upload>
          <a-button @click="del" v-if="selectedKeys[0] !== -1">
            删除图片
          </a-button>
          <a-button v-else @click="hardDelete">
            永久删除
          </a-button>
          <a-button v-if="selectedKeys[0] === -1" @click="removeRecycle">
            移出回收站
          </a-button>
        </a-space>
      </template>
    </toolbarTop>
    <div class="main">
      <div class="main-left">
        <a-menu v-model:selectedKeys="selectedKeys" mode="inline">
          <template v-for="item in data.data" :key="item.group_id">
            <a-menu-item @click="handleClick(item.group_id)" :class="{ recycle: item.group_id === -1 }">
              <span>{{ item.group_name }}</span>
              <svgIcon name="close" v-if="item.group_id !== -1" @click="handleDelGroup(item.group_id)" />
            </a-menu-item>
          </template>
        </a-menu>
      </div>
      <div class="main-right" v-if="list.data.data.length">
        <template v-if="type === 'multiple'">
          <div class="check-all">
            <a-checkbox
              v-model:checked="checkAll.checked"
              :indeterminate="checkAll.indeterminate"
              @change="onCheckAllChange"
            >
              全选
            </a-checkbox>
          </div>
          <a-checkbox-group v-model:value="list.checkedList" :options="list.data.data" @change="onChange">
            <template v-slot:label="{ file_path }">
              <img class="img" :src="file_path" alt="" />
            </template>
          </a-checkbox-group>
        </template>
        <a-radio-group v-else v-model:value="radioValue" @change="onChangeRadio">
          <template v-for="item in list.data.data" :key="item.file_id">
            <a-radio :value="item.file_id">
              <img class="img" :src="item.file_path" alt="" />
            </a-radio>
          </template>
        </a-radio-group>
      </div>
      <a-empty class="main-right" v-else />
    </div>
    <!-- 新增分组弹窗 -->
    <a-modal title="新增分组" v-model:visible="addModal.visibleAdd" @ok="handleAddOk">
      <a-input placeholder="请输入分组名称" v-model:value="addModal.name"></a-input>
    </a-modal>
  </div>
</template>

<script>
import { getCurrentInstance, ref, reactive, computed } from 'vue';
import { BASE_URL } from '../../utils/config';
import toolbarTop from '../../components/toolbar/toolbar-top.vue';
import { UploadOutlined, DownOutlined } from '@ant-design/icons-vue';
export default {
  name: 'Upload',
  components: {
    toolbarTop,
    UploadOutlined,
    DownOutlined
  },
  props: {
    type: {
      type: String,
      default: 'multiple'
    }
  },
  setup(props, { emit }) {
    let { ctx } = getCurrentInstance();

    let left = [
      {
        text: '刷新',
        handleName: 'refresh'
      },
      {
        text: '新增分组',
        handleName: 'add'
      }
    ];

    function refresh() {
      getData();
    }

    function del() {
      if (props.type === 'multiple' && list.checkedList.length === 0) {
        ctx.$message.error('请选择要删除的图片');
        return;
      }
      if (!radioValue.value) {
        ctx.$message.error('请选择要删除的图片');
        return;
      }
      ctx.$confirm({
        title: '提示',
        content: '是否确认删除图片?',
        async onOk() {
          let fileIds = props.type !== 'multiple' ? [radioValue.value] : list.checkedList;

          let res = await ctx.$fetch.post('/content.files/recovery', {
            file_ids: fileIds
          });
          list.checkedList = [];
          radioValue.value = '';
          ctx.$message.success(res.msg);
          handleClick(selectedKeys.value[0], true);
        },
        onCancel() {}
      });
    }

    function hardDelete() {
      if (props.type === 'multiple' && list.checkedList.length === 0) {
        ctx.$message.error('请选择要删除的图片');
        return;
      }
      if (!radioValue.value) {
        ctx.$message.error('请选择要删除的图片');
        return;
      }
      ctx.$confirm({
        title: '提示',
        content: '是否确认永久删除图片?',
        async onOk() {
          let fileIds = props.type !== 'multiple' ? [radioValue.value] : list.checkedList;

          let res = await ctx.$fetch.post('/content.files/deleteFiles', {
            file_ids: fileIds
          });
          list.checkedList = [];
          radioValue.value = '';
          ctx.$message.success(res.msg);
          handleClick(selectedKeys.value[0], true);
        },
        onCancel() {}
      });
    }

    function removeRecycle() {
      if (props.type === 'multiple' && list.checkedList.length === 0) {
        ctx.$message.error('请选择要移出的图片');
        return;
      }
      if (!radioValue.value) {
        ctx.$message.error('请选择要移出的图片');
        return;
      }
      ctx.$confirm({
        title: '提示',
        content: '是否确认移出回收站?',
        async onOk() {
          let fileIds = props.type !== 'multiple' ? [radioValue.value] : list.checkedList;

          let res = await ctx.$fetch.post('/content.files/restore', {
            file_ids: fileIds
          });
          list.checkedList = [];
          radioValue.value = '';
          ctx.$message.success(res.msg);
          handleClick(selectedKeys.value[0], true);
        },
        onCancel() {}
      });
    }

    let selectedKeys = ref([]);

    let data = reactive({
      data: []
    });
    let groupData = computed(() => data.data.filter((item) => item.group_id !== -1));
    async function getData(group_id) {
      let res = await ctx.$fetch.post('/content.files.group/index');
      data.data = res.data;
      if (data.data.length > 0) {
        handleClick(group_id || data.data[0].group_id);
        selectedKeys.value = group_id ? [group_id] : [data.data[0].group_id];
      }
    }
    getData();

    function handleDelGroup(group_id) {
      ctx.$confirm({
        title: '提示',
        content: '是否确认删除该分组?',
        async onOk() {
          let res = await ctx.$fetch.post('/content.files.group/delete', { group_id });
          ctx.$message.success(res.msg);
          refresh();
        },
        onCancel() {}
      });
    }

    let radioValue = ref('');

    function onChangeRadio(e) {
      radioValue.value = e.target.value;
      let file = list.data.data.find((d) => d.file_id === e.target.value);
      emit('file', { ...file });
    }

    async function handleClick(group_id, update) {
      if (group_id === selectedKeys.value[0] && !update) {
        return;
      }
      list.checkedList = [];
      onChange([]);
      let res = await ctx.$fetch.post('/content.files/index', { group_id });
      list.data = res.data;
      list.data.data = list.data.data.map((item) => {
        return {
          ...item,
          value: item.file_id
        };
      });
    }

    let list = reactive({
      data: {
        data: []
      },
      checkedList: []
    });

    let checkAll = reactive({
      checked: false,
      indeterminate: true
    });
    function onChange(checkedList) {
      checkAll.indeterminate = !!checkedList.length && checkedList.length < list.data.data.length;
      checkAll.checked = checkedList.length === list.data.data.length;
      let data = list.data.data.filter((d) => checkedList.includes(d.file_id));
      emit('file', data);
    }
    function onCheckAllChange(e) {
      list.checkedList = e.target.checked ? list.data.data.map((item) => item.file_id) : [];
      checkAll.indeterminate = false;
      let data = list.data.data.filter((d) => list.checkedList.includes(d.file_id));
      emit('file', data);
    }

    async function handleMove(id) {
      if (props.type === 'multiple' && list.checkedList.length === 0) {
        ctx.$message.error('请选择要移动的图片');
        return;
      }
      if (!radioValue.value) {
        ctx.$message.error('请选择要移动的图片');
        return;
      }

      let fileIds = props.type !== 'multiple' ? [radioValue.value] : list.checkedList;

      let res = await ctx.$fetch.post('/content.files.group/moveFiles', {
        group_id: id,
        file_ids: fileIds
      });
      list.checkedList = [];
      radioValue.value = '';
      ctx.$message.success(res.msg);
      handleClick(selectedKeys.value[0], true);
    }

    let addModal = reactive({
      visibleAdd: false,
      name: ''
    });
    function add() {
      addModal.name = '';
      addModal.visibleAdd = true;
    }
    async function handleAddOk() {
      if (!addModal.name.trim()) {
        ctx.$message.error('请输入分组名称');
        return;
      }
      let res = await ctx.$fetch.post('/content.files.group/add', {
        group_name: addModal.name,
        group_type: 'image'
      });
      ctx.$message.success(res.msg);
      refresh();
      addModal.name = '';
      addModal.visibleAdd = false;
    }

    let fileList = ref([]);
    function handleChange(info) {
      if (info.file.status === 'done') {
        let response = fileList.value[0].response;
        if (response && response.code === 1) {
          handleClick(selectedKeys.value[0], true);
          ctx.$message.success(response.msg);
        } else {
          ctx.$message.error(response.msg);
        }
      }
    }

    return {
      selectedKeys,
      left,
      refresh,
      add,
      del,
      hardDelete,
      removeRecycle,
      data,
      groupData,
      handleClick,
      list,
      checkAll,
      onCheckAllChange,
      onChange,
      handleMove,
      addModal,
      handleAddOk,
      fileList,
      handleChange,
      BASE_URL,
      radioValue,
      onChangeRadio,
      handleDelGroup
    };
  }
};
</script>

<style lang="scss" scoped>
.main {
  display: flex;
}
.main-left {
  width: 200px;
  padding: 20px;
}
.main-left ::v-deep {
  .ant-menu-item {
    display: flex;
    align-items: center;
    justify-content: space-between;
  }
  .ant-menu > .recycle {
    font-weight: bold;
    color: #e24650;
    border-top: 4px solid #ececec;
  }
  .recycle.ant-menu-item-selected {
    background-color: #f8c7c4;
    &::after {
      border-right: 3px solid #e7505a;
    }
  }
}
.main-right {
  flex: 1;
  padding: 20px;
  .img {
    width: 100px;
    height: 100px;
    margin: 10px;
  }
  .check-all {
    padding-bottom: 10px;
    border-bottom: 1px solid #e9e9e9;
  }
}
.ml5 {
  margin-left: 5px;
}
</style>
